<template>
  <view class="todo-receive-page">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
      </view>
      <view class="nav-center">
        <text class="nav-title">待办收文</text>
      </view>
      <view class="nav-right"> </view>
    </view>

    <!-- 搜索区域 -->
    <!-- <view class="search-section">
      <view class="search-form">
        <input
          class="search-input"
          v-model="searchForm.sourceDocumentTitle"
          placeholder="请输入文件标题"
        />
        <view class="search-buttons">
          <text class="search-btn" @click="handleSearch">查询</text>
          <text class="reset-btn" @click="handleReset">重置</text>
        </view>
      </view>
    </view> -->

    <!-- 列表区域 -->
    <view class="list-section">
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <text class="loading-text">加载中...</text>
      </view>

      <view class="todo-list" v-else-if="todoList.length > 0">
        <view class="todo-item" v-for="item in todoList" :key="item.id">
          <view class="item-header">
            <view class="item-title">
              <text class="title-text">{{
                item.sourceDocumentTitle || item.title || '无标题'
              }}</text>
              <view
                :class="['urgency-badge', `urgency-${item.sourceDocumentUrgencyLevel || 'normal'}`]"
              >
                <text class="badge-text">{{
                  getUrgencyText(item.sourceDocumentUrgencyLevel)
                }}</text>
              </view>
            </view>
            <text class="item-time">{{
              formatDateTime(item.receiveDocumentTime || item.createdAt)
            }}</text>
          </view>
          <view class="item-content">
            <text class="item-desc">来文单位：{{ item.sourceCompanyName || '-' }}</text>
            <text class="item-desc">来文文号：{{ item.receiveDocumentSymbol || '-' }}</text>
            <text class="item-desc">当前步骤：{{ item.currentStepName || '-' }}</text>
            <text class="item-desc">下一步骤：{{ item.nextStepName || '-' }}</text>
          </view>
          <view class="item-footer">
            <view class="item-info">
              <text class="info-text"
                >收文时间：{{ formatDateTime(item.receiveDocumentTime || item.createdAt) }}</text
              >
            </view>
            <view class="item-actions">
              <text class="action-btn primary" @click.stop="handleView(item)">审批</text>
            </view>
          </view>
        </view>
      </view>

      <view class="empty-state" v-else>
        <text class="empty-icon">📬</text>
        <text class="empty-text">暂无待审批收文</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getMyDistributesByRole, type ReceiveDocumentDistributeItem } from '@/Api/receive'

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = ref({
  sourceDocumentTitle: '',
})

// 待审批列表数据
const todoList = ref<ReceiveDocumentDistributeItem[]>([])
const originalList = ref<ReceiveDocumentDistributeItem[]>([])

// 返回上一页
const goBack = () => {
  const pages = getCurrentPages()
  if (pages.length <= 1) {
    uni.reLaunch({
      url: '/pages/index/index',
    })
  } else {
    uni.navigateBack({
      delta: 1,
    })
  }
}

// 搜索处理
const handleSearch = () => {
  if (!searchForm.value.sourceDocumentTitle.trim()) {
    todoList.value = [...originalList.value]
    return
  }

  const keyword = searchForm.value.sourceDocumentTitle.trim().toLowerCase()
  todoList.value = originalList.value.filter((item) => {
    const title = (item.sourceDocumentTitle || item.title || '').toLowerCase()
    const company = (item.sourceCompanyName || '').toLowerCase()
    const symbol = (item.receiveDocumentSymbol || '').toLowerCase()
    return title.includes(keyword) || company.includes(keyword) || symbol.includes(keyword)
  })
}

// 重置搜索
const handleReset = () => {
  searchForm.value.sourceDocumentTitle = ''
  todoList.value = [...originalList.value]
}

// 查看详情并审批
const handleView = (item: any) => {
  uni.navigateTo({
    url: `/pages/document/receive/todo/detail?id=${item.id}&source=todo&receiveStepName=${
      item.receiveStepName || ''
    }&receiveStepOrder=${item.receiveStepOrder || ''}`,
  })
}

// 获取紧急程度文本
const getUrgencyText = (level?: string): string => {
  const textMap: Record<string, string> = {
    low: '低',
    normal: '普通',
    high: '高',
    urgent: '紧急',
  }
  return textMap[level || 'normal'] || '普通'
}

// 格式化日期时间
const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}/${month}/${day}`
}

// 加载待审批列表数据
const loadData = async () => {
  try {
    loading.value = true

    // 调用待办收文接口
    const response = await getMyDistributesByRole()

    if (response.code === 200) {
      originalList.value = response.data || []
      todoList.value = [...originalList.value]
      console.log('[待审批收文列表加载成功]', todoList.value.length)
    } else {
      throw new Error(response.message || '加载失败')
    }
  } catch (error: any) {
    console.error('[加载待审批收文列表失败]', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
  }
}

// 页面显示时刷新（首次加载和从详情页返回时都会触发）
onShow(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.todo-receive-page {
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;

  /* 顶部导航 */
  .nav-header {
    background: #1a3582;
    padding: 46px 32rpx 20rpx 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: white;
    flex-shrink: 0;

    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .back-icon {
        font-size: 40rpx;
        font-weight: bold;
      }
    }

    .nav-center {
      flex: 1;
      text-align: center;

      .nav-title {
        font-size: 36rpx;
        font-weight: bold;
      }
    }

    .nav-right {
      min-width: 22px;
    }
  }

  /* 搜索区域 */
  .search-section {
    padding: 24rpx 32rpx;
    background: white;
    position: relative;
    z-index: 3;

    .search-form {
      display: flex;
      align-items: center;
      gap: 16rpx;

      .search-input {
        flex: 1;
        height: 80rpx;
        padding: 0 24rpx;
        border: 1rpx solid #e5e7eb;
        border-radius: 12rpx;
        font-size: 28rpx;
        background: #f8f9fa;
      }

      .search-buttons {
        display: flex;
        gap: 16rpx;

        .search-btn,
        .reset-btn {
          padding: 16rpx 32rpx;
          border-radius: 12rpx;
          font-size: 26rpx;
          text-align: center;
        }

        .search-btn {
          background: #1678ff;
          color: white;
        }

        .reset-btn {
          background: #f3f4f6;
          color: #666;
        }
      }
    }
  }

  /* 统计信息 */
  .stats-info {
    padding: 24rpx 32rpx;
    flex-shrink: 0;

    .stat-item {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 16rpx;
      padding: 24rpx 32rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);

      .stat-label {
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.9);
        font-weight: 500;
      }

      .stat-value {
        font-size: 40rpx;
        font-weight: bold;
        color: white;
      }
    }
  }

  /* 列表区域 */
  .list-section {
    flex: 1;
    overflow: hidden;
    padding: 24rpx 32rpx;
    display: flex;
    flex-direction: column;

    .loading-state {
      text-align: center;
      padding: 60rpx 0;

      .loading-text {
        font-size: 28rpx;
        color: #999;
      }
    }

    .todo-list {
      flex: 1;
      overflow-y: auto;

      .todo-item {
        background: white;
        border-radius: 16rpx;
        padding: 24rpx;
        margin-bottom: 16rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
        transition: all 0.3s ease;

        &:active {
          opacity: 0.8;
        }

        .item-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16rpx;

          .item-title {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 12rpx;
            flex-wrap: wrap;

            .title-text {
              font-size: 28rpx;
              font-weight: 600;
              color: #333;
              flex: 1;
              min-width: 0;
            }

            .urgency-badge {
              padding: 6rpx 16rpx;
              border-radius: 8rpx;
              font-size: 20rpx;
              flex-shrink: 0;

              .badge-text {
                font-size: 20rpx;
              }

              &.urgency-low {
                background: #f0f9ff;
                border: 1px solid #bae6fd;

                .badge-text {
                  color: #0284c7;
                }
              }

              &.urgency-normal {
                background: #ecf5ff;
                border: 1px solid #d9ecff;

                .badge-text {
                  color: #1890ff;
                }
              }

              &.urgency-high {
                background: #fef3c7;
                border: 1px solid #fde68a;

                .badge-text {
                  color: #d97706;
                }
              }

              &.urgency-urgent {
                background: #fee2e2;
                border: 1px solid #fecaca;

                .badge-text {
                  color: #dc2626;
                }
              }
            }
          }

          .item-time {
            font-size: 22rpx;
            color: #ccc;
            flex-shrink: 0;
            margin-left: 4px;
          }
        }

        .item-content {
          margin-bottom: 16rpx;

          .item-desc {
            display: block;
            font-size: 24rpx;
            color: #999;
            line-height: 1.5;
            margin-bottom: 6rpx;
          }
        }

        .item-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .item-info {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 16rpx;
            flex-wrap: wrap;

            .info-text {
              font-size: 22rpx;
              color: #ccc;
            }
          }

          .item-actions {
            display: flex;
            gap: 20rpx;

            .action-btn {
              padding: 10rpx 20rpx;
              border-radius: 8rpx;
              font-size: 30rpx;
              color: #666;
              background: #f5f7fa;
              display: flex;
              align-items: center;
              justify-content: center;

              &.primary {
                background: #1678ff;
                color: white;
              }
            }
          }
        }
      }
    }

    .empty-state {
      text-align: center;
      padding: 80rpx 0;

      .empty-icon {
        font-size: 80rpx;
        display: block;
        margin-bottom: 24rpx;
      }

      .empty-text {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
}
</style>
